<template>
  <div class="search-card head">
    <div class="input-view">
      <el-autocomplete
        v-model="keyword"
        :fetch-suggestions="querySearch"
        popper-class="my-autocomplete"
        placeholder="可查找企业名称、经营范围"
        @select="handleSelect"
        @keyup.enter="handleKeywordSearch"
      >
        <template #suffix>
          <Icon icon="ep:search" @click="handleKeywordSearch" />
        </template>
        <template #default="{ item }">
          <div class="value">{{ item }}</div>
        </template>
      </el-autocomplete>
    </div>
    <el-text class="many" @click="onButtonClick">更多筛选>></el-text>
  </div>
  <div class="crm-workbench">
    <el-row :gutter="10">
      <el-col :span="8">
        <div class="workEchart">
          <div class="workTitle">
            <div class="titleLeft">
              <div class="titleImage">
                <div class="imgBox"></div>
              </div>
              <div class="titleTxt">
                <p>{{ limitClaim.receiveLimit }}</p>
                <span>每日领取上限</span>
              </div>
            </div>
            <div class="titleRight">
              <div class="rightTop">
                <span class="num">{{ limitClaim.receiveNumber.toLocaleString('en-US') }}</span>
                <span class="numTxt">领取数量</span>
              </div>
              <div class="rightBottom">
                <span class="num">{{ limitClaim.followNumber.toLocaleString('en-US') }}</span>
                <span class="numTxt">跟进次数</span>
              </div>
            </div>
          </div>
          <div class="workCotent">
            <Echart :height="174" :options="echartsOption" />
          </div>
        </div>
      </el-col>
      <el-col :span="8">
        <ContentWrap
          title="精选模板"
          class="contentWarp"
          button="更多>>"
          @button-click="onButtonClickTemp()"
        >
          <div class="taglist h-200px">
            <el-space wrap v-if="systemMap.length">
              <el-tag
                v-for="(item, index) in systemMap"
                :style="{ color: '#fff', background: ColorMap[index % 4] }"
                :key="item.id"
                @click="useTemplate(true, item)"
                >{{ item.templateName }}</el-tag
              >
            </el-space>
            <el-empty style="padding: 0; height: 190px" v-else description="暂无数据" />
          </div>
        </ContentWrap>
      </el-col>
      <el-col :span="8">
        <ContentWrap
          class="contentWarp"
          title="热门搜索"
          button="更多>>"
          @button-click="onButtonClick()"
        >
          <div class="taglist h-200px overflow-hidden">
            <el-space wrap v-if="hotKeywordList.length">
              <el-tag
                v-for="(item, i) in hotKeywordList"
                @click="clickKeyword(item)"
                :style="{ color: '#fff', background: ColorMap[i % 4] }"
                :key="i"
                >{{ item }}</el-tag
              >
            </el-space>
            <el-empty style="padding: 0; height: 190px" v-else description="暂无数据" />
          </div>
        </ContentWrap>
      </el-col>
    </el-row>

    <ContentWrap class="contentWarp" v-loading="isloading">
      <div class="crm-workbench__body">
        <div class="form-title flex justify-between">
          <el-text> 近30天新增企业 </el-text>
          <el-button type="primary" :icon="Unlock" @click="onClickUnlock">批量领取</el-button>
        </div>
        <div class="page-box">
          <CompanyList
            :list="latestCompanyList"
            @refresh-val="refreshData"
            @show-item="onEntNameClick"
          />
        </div>
      </div>
      <Pagination
        :total="latestCompanyTotal"
        :page="latestCompanyQueryParam.pageNo"
        :limit="latestCompanyQueryParam.pageSize"
        @pagination="getLatestDataList"
      />
    </ContentWrap>
    <!-- 企业详情 -->
    <EnterpriseDetails ref="companyDetail" @refresh-val="detailRefreList" />
    <!-- 更多模板 -->
    <Dialog v-model="useTmplVisible" title="选择模板" width="950px">
      <use-tmpl ref="useTmplRef" v-if="useTmplVisible" />
      <template #footer>
        <el-button @click="useTmplVisible = false">取 消</el-button>
        <el-button type="primary" @click="useTemplate">使 用</el-button>
      </template>
    </Dialog>
  </div>
  <TableSelect
    :modelValue="selectedItems"
    ref="tableSelect"
    @update:model-value="receiveCompany"
    @get-table-fun="getTableFun"
  >
    <el-table-column prop="companyInfo.companyName" label="企业名称" align="center" />
    <el-table-column prop="companyInfo.numberCount" label="联系电话(条)" align="center" />
    <el-table-column label="解锁状态" align="center">
      <template #default="scope">
        <el-tag type="info" v-if="scope.row.companyInfo.received"
          >已被{{ scope.row.companyInfo.receiveUser }}领取</el-tag
        >
        <el-tag type="primary" v-else>待领取</el-tag>
      </template>
    </el-table-column>
  </TableSelect>
</template>

<script setup lang="ts">
import CompanyList from '../advanceSearch/CompanyList.vue'
import * as CompanyApi from '@/api/ent/company'
import { Unlock } from '@element-plus/icons-vue'
import * as advanceApi from '@/api/ent/advanceSearch/index'
import EnterpriseDetails from '../components/EnterpriseDetaill/index.vue'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import UseTmpl from '../advanceSearch/superSearch/UseTmpl.vue'
import { useEntStore } from '@/store/modules/ent'
import { formatDate } from '@/utils/public'
import { EChartsOption } from 'echarts'

const useTmplVisible = ref(false)
const useTmplRef = ref(null)
const companyDetail = ref(null)
const router = useRouter()
const isloading = ref(false)
const systemMap = ref([])
// 领取上限
const limitClaim = ref({
  followNumber: 0,
  receiveLimit: 0,
  receiveNumber: 0
})
const selectedItems = ref([])
const tableSelect = ref(null)
// 批量解锁
const receiveCompany = async (val) => {
  let ids = []
  if (val.length) {
    val.forEach((item) => {
      ids.push(item.companyInfo.cid)
    })
    const res = await advanceApi.companyReceive({ ids })
    if (res) ElMessage.success('解锁成功!')
    refreshVals()
  }
}

// 表格分页
const getTableFun = async (val) => {
  latestCompanyQueryParam.value.pageNo = val.pageNo
  latestCompanyQueryParam.value.pageSize = val.pageSize
  let data = { page: val.pageNo, limit: val.pageSize }
  await getLatestDataList(data)
  onClickUnlock()
}
// 刷新/分页切换
const refreshVals = () => {
  if (latestCompanyQueryParam.value) {
    isloading.value = true
    getLatestDataList({
      page: latestCompanyQueryParam.value.pageNo,
      limit: latestCompanyQueryParam.value.pageSize
    })
  }
}
//显示弹窗
const onClickUnlock = () => {
  tableSelect.value.openDialogVisible({
    value: latestCompanyList.value,
    totals: latestCompanyTotal.value,
    pageNo: latestCompanyQueryParam.value.pageNo,
    pageSize: latestCompanyQueryParam.value.pageSize
  })
}
const ColorMap = ref([
  'rgb(132, 202, 176)',
  'rgb(188, 158, 221)',
  'rgb(125, 179, 217)',
  'rgb(140, 163, 205)'
])

const entStore = useEntStore()
// select列表的条件
onBeforeMount(async () => {
  await entStore.setAdvanceCond()
})
onMounted(() => {
  systemTmpLsit()
  getTodayCout()
})

// TODO: 这里要进入到查询页面的路由中
const onButtonClick = (param) => {
  router.push('/ent/search/result')
}
// 近30天新增企业 - 查询参数
const latestCompanyQueryParam = ref({
  pageNo: 1,
  pageSize: 15
})
// 近30天新增企业 - 列表
const latestCompanyList = ref([])
const latestCompanyTotal = ref(0)

// 查找本地搜索记录
const keyword = ref('')
const { wsCache } = useCache()

const querySearch = (queryString: string, cb) => {
  let data = wsCache.get(CACHE_KEY.ENT_SEARCH)
  if (data) {
    const results = queryString ? data.filter(createFilter(queryString)) : data
    cb(results)
  } else {
    cb([])
  }
}
const createFilter = (queryString) => {
  return (restaurant) => {
    return restaurant.toLowerCase().indexOf(queryString.toLowerCase()) === 0
  }
}
// 关键词查询方法
const handleKeywordSearch = () => {
  if (keyword.value != '') {
    let cached = wsCache.get(CACHE_KEY.ENT_SEARCH)
    if (!cached) {
      cached = [keyword.value]
    } else {
      cached.indexOf(keyword.value) == -1 && cached.push(keyword.value)
      // 控制一下长度，不超过15个
      cached.length > 15 && cached.pop()
    }
    wsCache.set(CACHE_KEY.ENT_SEARCH, cached)
    CompanyApi.searchReport({ type: 'keywordSearch', data: keyword.value })
    router.push(`/ent/search/result?keyword=${keyword.value}`)
  }
}

const handleSelect = (item) => {
  router.push(`/ent/search/result?keyword=${item}`)
}
onMounted(async () => {
  await getLatestDataList()

  await getHotKeywordList()
})

// 随便写一下，没什么必要
interface IPage {
  page: number
  limit: number
}

// 近30天新增企业列表
const getLatestDataList = async (page: IPage) => {
  isloading.value = true
  if (page) {
    latestCompanyQueryParam.value.pageNo = page.page
    latestCompanyQueryParam.value.pageSize = page.limit
  }
  let ids
  const { results, total } = await CompanyApi.getLatestCompanyList(latestCompanyQueryParam.value)
  if (results.length) {
    ids = results.map((element) => element.companyInfo.cid)
    const res = await advanceApi.companyGetStatus({ ids: ids })
    latestCompanyList.value = mergeValues(results, res)
  } else {
    latestCompanyList.value = results
  }
  latestCompanyTotal.value = total
  isloading.value = false
}
const mergeValues = (arrayA, objectB) => {
  arrayA.forEach((itemA) => {
    let key = itemA.companyInfo.cid
    if (objectB[key]) {
      Object.assign(itemA.companyInfo, objectB[key])
    }
  })
  return arrayA
}

// TODO: 处理下关键词的点击查询
const clickKeyword = async (keyword) => {
  CompanyApi.searchReport({ type: 'keywordSearch', data: keyword })
  router.push(`/ent/search/result?keyword=${keyword}`)
}

const hotKeywordList = ref(['精准大数据'])

// TODO: 缓存到sessionStorage 中
const getHotKeywordList = async () => {
  hotKeywordList.value = await CompanyApi.getHotKey()
}

// 系统模板列表
const systemTmpLsit = async () => {
  const data = await advanceApi.systemSimpleList()
  if (data.length) {
    data.forEach((item) => {
      item.createTime = formatDate(item.createTime)
    })
  }
  systemMap.value = data
}

//详情
const onEntNameClick = async (item, val, index) => {
  //                            显示             cid        锚点?  下标
  companyDetail.value.setDrawer(true, item.companyInfo.cid, val, index)
}
// 详情的刷新
const detailRefreList = (data) => {
  let index = sessionStorage.getItem('companyIndex')
  latestCompanyList.value[index].companyInfo.receiveUser = data.receiveUser
  latestCompanyList.value[index].companyInfo.received = data.received
}
// 刷新
const refreshData = () => {
  getLatestDataList()
}
// 精选模板更多
const onButtonClickTemp = () => {
  sessionStorage.setItem('templateType', 'system')
  useTmplVisible.value = true
}
// 使用模板
const useTemplate = (val, item) => {
  let data
  if (val == true) {
    sessionStorage.setItem('useTemplate', item.templateContent)
  } else {
    sessionStorage.setItem('useTemplate', JSON.stringify(useTmplRef.value.TemlateValue()))
  }
  router.push(`/ent/advanceSearch/index?keyword=true`)
}
const getTodayCout = async () => {
  const res = await CompanyApi.todayCout()
  let xAxisData = []
  let yAxisReceiveNumber = []
  let yAxisFollowNumber = []
  res.lineData.forEach((element) => {
    xAxisData.push(formatDate(element.createTime))
    yAxisReceiveNumber.push(element.receiveNumber)
    yAxisFollowNumber.push(element.followNumber)
  })
  echartsOption.xAxis['data'] = xAxisData
  echartsOption.series[0]['data'] = yAxisReceiveNumber
  echartsOption.series[1]['data'] = yAxisFollowNumber
  res.receiveNumber = res.receiveNumber ? res.receiveNumber : 0
  res.followNumber = res.followNumber ? res.followNumber : 0
  limitClaim.value = res
}
const echartsOption = reactive<EChartsOption>({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  legend: {
    top: '10%'
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: [],
    axisLabel: {
      //x轴 强制显示全
      // interval: 0
    }
  },
  yAxis: {
    type: 'value',
    boundaryGap: [0, 0.01]
  },
  series: [
    {
      name: '领取数量',
      type: 'bar',
      data: [],
      itemStyle: {
        color: '#9fceff',
        borderRadius: [5, 5, 0, 0]
      }
    },
    {
      name: '跟进次数',
      type: 'bar',
      data: [],
      itemStyle: {
        color: '#409eff',
        borderRadius: [5, 5, 0, 0]
      }
    }
  ]
}) as EChartsOption
</script>

<style scoped lang="scss">
/* 保持原有布局，只优化样式细节 */

/* 头部搜索区域优化 */
.head {
  padding: 50px;
  border-bottom: 1px solid #e5e7eb;
  background: linear-gradient(135deg, #0052cc 0%, #1d4ed8 100%);
  border-radius: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 15px;
  box-shadow: 0 4px 12px rgba(0, 82, 204, 0.15);
  transition: all 0.3s ease;
}

.head:hover {
  box-shadow: 0 6px 20px rgba(0, 82, 204, 0.2);
}

.input-view {
  display: flex;
  justify-content: center;
  position: relative;

  .el-input {
    width: 720px;
  }

  :deep(.el-input) {
    width: 970px;
  }

  :deep(.el-input__wrapper) {
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
  }

  :deep(.el-input__wrapper:hover) {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }

  :deep(.el-input__wrapper.is-focus) {
    box-shadow: 0 0 0 3px rgba(0, 82, 204, 0.2);
  }

  .search-icon {
    position: absolute;
    top: 0;
    right: 0;
    border-radius: 0 8px 8px 0;
    background: #fff;
    font-size: 16px;
    width: 54px;
    height: 42px;
    text-align: center;
    box-sizing: border-box;
    border-left: 1px solid #ededed;
    font-weight: 700;
    color: #0052cc;
    display: flex;
    justify-content: center;
    align-items: center;
    transition: all 0.2s ease;
  }

  .search-icon:hover {
    background: #f0f7ff;
  }

  :deep(.el-input__inner) {
    border: none;
    height: 40px;
    border-top-right-radius: 0;
    border-bottom-right-radius: 0;
  }
}

.many {
  color: #fff;
  margin-left: 10px;
  cursor: pointer;
  padding: 8px 16px;
  border-radius: 6px;
  transition: all 0.2s ease;
  font-weight: 500;
}

.many:hover {
  background: rgba(255, 255, 255, 0.1);
  transform: translateY(-1px);
}

/* 工作台区域优化 */
.workEchart {
  height: calc(100% - 15px);
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;

  &:hover {
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
    transform: translateY(-2px);
  }

  $txtMargin: 5px;

  .workTitle {
    flex: 1;
    margin-bottom: $txtMargin;
    display: flex;
    justify-content: space-between;

    .titleRight {
      flex: 1;
      margin-left: $txtMargin;
      border-radius: 8px;
      display: flex;
      flex-direction: column;

      div {
        padding: 0 40px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        transition: all 0.2s ease;

        .num {
          font-size: 32px;
          font-weight: 600;
          margin-bottom: $txtMargin;
          color: #1f2937;
          opacity: 0.9;
        }

        .numTxt {
          font-size: 12px;
          color: #6b7280;
          opacity: 0.9;
        }
      }

      .rightTop {
        flex: 1;
        background-color: #fff;
        border-radius: 8px;
        margin-bottom: 4px;
        border: 1px solid #f0f0f0;
      }

      .rightBottom {
        flex: 1;
        background-color: #fff;
        border-radius: 8px;
        margin-top: 4px;
        border: 1px solid #f0f0f0;
      }
    }

    .titleLeft {
      flex: 1.3;
      margin-right: $txtMargin;
      border-radius: 8px;
      background-color: #fff;
      display: flex;
      border: 1px solid #f0f0f0;

      .titleImage {
        flex: 1;
        display: flex;
        justify-content: center;
        align-items: center;

        .imgBox {
          width: 70%;
          height: 75%;
          background: url('@/assets/imgs/search-bgc.png') no-repeat;
          background-size: 100% 100%;
        }
      }

      .titleTxt {
        flex: 1;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;

        p {
          margin: 0;
          font-size: 32px;
          font-weight: 600;
          margin-bottom: $txtMargin;
          color: #1f2937;
          opacity: 0.9;
        }

        span {
          margin-top: $txtMargin;
          font-size: 12px;
          color: #6b7280;
          opacity: 0.9;
        }
      }
    }
  }

  .workCotent {
    margin-top: 5px;
    flex: 2;
    background-color: #fff;
    border-radius: 8px;
    border: 1px solid #f0f0f0;
  }
}

/* ContentWrap 卡片优化 */
:deep(.contentWarp) {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  border-radius: 8px;
  border: 1px solid #f0f0f0;
  transition: all 0.3s ease;

  &:hover {
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
    transform: translateY(-2px);
  }

  .el-card__header {
    border-bottom: 1px solid #f0f0f0;
    background: #fafbfc;
    border-radius: 8px 8px 0 0;

    div {
      font-weight: 600;
      opacity: 0.9;
    }

    .flex {
      div {
        .text-16px {
          position: relative;
          color: #1f2937;
          font-size: 16px;
          font-weight: 600;
        }

        .text-16px::before {
          content: '';
          position: absolute;
          top: 3px;
          left: -10px;
          width: 4px;
          height: 18px;
          background-color: #0052cc;
          border-radius: 2px;
        }
      }
    }
  }

  .el-card__body {
    div {
      .taglist {
        overflow-y: auto;

        /* 美化滚动条样式 */
        &::-webkit-scrollbar {
          width: 6px;
        }

        &::-webkit-scrollbar-track {
          background: #f1f3f4;
          border-radius: 3px;
        }

        &::-webkit-scrollbar-thumb {
          background: linear-gradient(180deg, #c1c9d2 0%, #a8b4c0 100%);
          border-radius: 3px;
          transition: all 0.2s ease;
        }

        &::-webkit-scrollbar-thumb:hover {
          background: linear-gradient(180deg, #0052cc 0%, #1d4ed8 100%);
          box-shadow: 0 2px 4px rgba(0, 82, 204, 0.3);
        }

        /* Firefox 滚动条样式 */
        scrollbar-width: thin;
        scrollbar-color: #c1c9d2 #f1f3f4;

        .el-tag {
          cursor: pointer;
          font-size: 13px;
          padding: 12px 16px;
          border-radius: 6px;
          font-weight: 500;
          transition: all 0.2s ease;
          border: none;
        }

        .el-tag:hover {
          transform: translateY(-1px);
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
        }
      }
    }
  }
}

/* 企业列表区域优化 */
.crm-workbench__body {
  max-width: 80%;
  margin: 0 auto;

  .form-title {
    color: #1f2937;
    padding: 0 0 20px 0;
    border-bottom: 1px solid #e5e7eb;
    font-weight: 600;

    .el-text {
      font-size: 18px;
      font-weight: 600;
      position: relative;
    }

    .el-text::before {
      content: '';
      position: absolute;
      top: 3px;
      left: -12px;
      width: 4px;
      height: 20px;
      background-color: #0052cc;
      border-radius: 2px;
    }
  }

  .page-box {
    padding-top: 10px;
    width: 100%;
    overflow: hidden;
  }
}

/* 按钮优化 */
:deep(.el-button--primary) {
  background-color: #0052cc;
  border-color: #0052cc;
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.2s ease;
}

:deep(.el-button--primary:hover) {
  background-color: #1d4ed8;
  border-color: #1d4ed8;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 82, 204, 0.3);
}

/* 标签优化 */
:deep(.el-tag--primary) {
  background-color: #0052cc;
  border-color: #0052cc;
  color: white;
}

:deep(.el-tag--info) {
  background-color: #6b7280;
  border-color: #6b7280;
  color: white;
}

/* 自动完成下拉优化 */
:deep(.my-autocomplete) {
  .el-autocomplete-suggestion__list {
    border-radius: 8px;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
    border: 1px solid #e5e7eb;
  }

  .el-autocomplete-suggestion__item {
    padding: 12px 16px;
    transition: all 0.2s ease;
  }

  .el-autocomplete-suggestion__item:hover {
    background: #f0f7ff;
    color: #0052cc;
  }
}

.value {
  font-size: 14px;
  color: #374151;
}

/* 对话框优化 */
:deep(.el-dialog) {
  border-radius: 8px;
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid #e5e7eb;
  background: #fafbfc;
}

/* 分页优化 */
:deep(.el-pagination) {
  .el-pager li {
    border-radius: 4px;
    margin: 0 2px;
  }

  .el-pager li.is-active {
    background-color: #0052cc;
    color: white;
  }
}

/* 加载状态优化 */
:deep(.el-loading-mask) {
  background-color: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(4px);
}

/* 级联面板优化 */
:deep(.el-cascader-panel.is-bordered) {
  border: none !important;
}

/* 响应式优化 */
@media (max-width: 768px) {
  .head {
    padding: 30px 20px;
    flex-direction: column;
    gap: 16px;
  }

  .input-view {
    :deep(.el-input) {
      width: 100%;
    }
  }

  .crm-workbench__body {
    max-width: 100%;
    padding: 0 16px;
  }
}
</style>
